package com.NetSunWeiQin.chapter05.exercise;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;

public class ApiPostDemo {


    public static  void communicate() throws Exception {
        String host = "localhost";
        int port = 8086;
        Socket socket = new Socket(host, port);
//        socket.connect(new InetSocketAddress(Inet4Address.getByName(host), port)); //建立 TCP 连接



        /*构建请求头 */
//        StringBuffer sb = new StringBuffer("GET " + "/test/test2" + " HTTP/1.1\r\n");
//        sb.append("Host: " + host + ":" + port + "\r\n");
//        sb.append("Accept: */*\r\n");
//        sb.append("Accept-Language: en-US,en;q=0.5\r\n");
//        sb.append("Accept-Encoding: gzip, deflate\r\n");
//        sb.append("User-Agent: HTTPClient\r\n");
//        sb.append("Connection: Keep-Alive\r\n\r\n");
        //   OutputStream socketOut = socket.getOutputStream();
        // socketOut.write(sb.toString().getBytes());
        //  socketOut.flush();   //发送 http  请求


        String[] headers = {"GET /test/test2 HTTP/1.1\r\n", "Host: www.baidu.com\r\n", "\r\n"};
        OutputStream out = socket.getOutputStream();
        for (int i = 0; i < headers.length; i++)
            out.write(headers[i].getBytes());
        out.flush();



        /*获取返回数据*/
/*        InputStream socketIn = socket.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = -1;
        while ((len = socketIn.read(buff)) != -1) {
            buffer.write(buff, 0, len);
        }

        System.out.println(new String(buffer.toByteArray()));*/



        InputStream  in = socket.getInputStream();
        StringBuffer buf = new StringBuffer();
        socket.setSoTimeout(2000);
        int len = -1;
        byte[] b = new byte[1024] ;
        while(true) {
            try {
                len = in.read(b);
                buf.append(new String(b,0,len, StandardCharsets.UTF_8));
            } catch(SocketTimeoutException e) {
                in.close();
                out.close();
                socket.close();
                break;
            }
        }
        System.out.println("获取的结果是" + buf.toString());
/*
    InputStream socketIn=socket.getInputStream();
    BufferedReader br=new BufferedReader(new InputStreamReader(socketIn));
    String data;
    while((data=br.readLine())!=null){
      System.out.println(data);
    }
*/

        socket.close();
    }


    public static void main(String args[]) throws Exception {
        communicate();
    }
}


